//
//  ServiceAdvertiser.java
//  SketchServer
//
//  Created by Brian on 10/11/09.
//  Copyright 2009 Tellart. All rights reserved.
//

import java.io.IOException;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import java.net.InetAddress;

public class ServiceAdvertiser {
    
    private JmDNS jmdns = null;
    private ServiceInfo serviceInfo;
    
    public ServiceAdvertiser(InetAddress addr, String serviceId, String serviceProtocol, int port, String desc) throws IOException {
        String name;
        try {
            //get the computer name
            name = InetAddress.getLocalHost().getHostName();
            //name = addr.getCanonicalHostName();
            name = name.toLowerCase().replaceAll("[^a-z]", "");
            System.out.println("ServiceAdvertiser() name="+name);
        } catch (Exception e) {
            name = "SketchServer";
        }
        String id = "_"+serviceId+"._"+serviceProtocol+".local.";
        desc = "address="+addr.getHostAddress();
        System.out.println("ServiceAdvertiser: creating on interface "+addr+" for "+name+" ("+id+") on port " + port +". Description: " + desc);
        //this.serviceInfo = ServiceInfo.create(id, name, port, desc);
        if (jmdns == null) jmdns = JmDNS.create(addr);
        this.serviceInfo = ServiceInfo.create(id, name, port, 0, 0, desc);
    }
    
    
    /*
     * advertises the server over JmDNS
     *
     */
    public void start() throws IOException {
        System.out.println("ServiceAdvertiser.start - " + this.serviceInfo.toString());
        this.jmdns.registerService(this.serviceInfo);
    }
    
    public void stop() {
        System.out.println("ServiceAdvertiser.stop - " + this.serviceInfo.toString());
        if (jmdns != null) jmdns.close();
    }

}
